package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.intercepror.UserHolder;
import com.tanhua.utils.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SmallVideosService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发布视频时，清空缓存数据
    //@CacheEvict(value = "videos",allEntries = true)
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //1、视频上传到FastDFS获取请求地址
        String filename = videoFile.getOriginalFilename(); //xxx.jpg
        filename = filename.substring(filename.lastIndexOf(".")+1);
        //上传到阿里云获取file_id
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(),
                filename, null);//输入流，长度，后缀名，元数据
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        //2、图片上传到阿里云OSS，获取请求地址
        String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(),
                videoThumbnail.getInputStream());
        //3、创建Videos对象
        Video video = new Video();
        video.setCreated(System.currentTimeMillis());
        video.setUserId(UserHolder.getUserId());
        video.setText("我就是我，是颜色不一样的烟火");
        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);
        //4、调用API保存
        videoApi.save(video);
    }


    //借助SpringCache将数据存入到redis中

    //查询视频列表（推荐数据，所有的视频数据）
    //@Cacheable(value = "videos",key = "T(com.tanhua.server.intercepror.UserHolder).userId +
    // '_' + #page + '_' + #pagesize")  //用户id_3_10
    public PageResult findVideos(Integer page, Integer pagesize) { //2
        //1、从redis中查询推荐的数据 （视频id的字符串）
        String key = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        String value = redisTemplate.opsForValue().get(key);  //10条数据
        //2、判断推荐数据是否存在
        List<Video> list = new ArrayList<>();
        if(!StringUtils.isEmpty(value)) {
            //3、如果数据存在，调用API根据视频id，查询视频数据   List<video>
            String[] vids = value.split(",");
            list = videoApi.findByIds(vids,page,pagesize);
        }else {
            //4、如果数据不存在，查询所有视频（倒叙展示）        List<video>
            list = videoApi.findAll(page,pagesize);
        }
        //查询所有发布人
        List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);
        //构建map集合
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids);
        //5、将List<video>转化成List<videovo>
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            Long userId = video.getUserId();
            UserInfo userInfo = map.get(userId);
            VideoVo vo = VideoVo.init(userInfo, video);
            vos.add(vo);
        }
        //6、构造返回PageResult
        return new PageResult(page,pagesize,0l,vos);
    }

    @Autowired
    private MqMessageService mqMessageService;

    //视频点赞
    public void like(String videoId) {
        //业务逻辑自行实现
        System.out.println("对动态点赞："+videoId);
        //发布评分消息
        mqMessageService.sendLogMessage(UserHolder.getUserId(),"0302","log.video",videoId);
    }
}
